package com.ruyuan.commodity.controller.seller;

import com.ruyuan.commodity.exception.ServiceException;
import com.ruyuan.commodity.common.mamager.GoodsQuantityManager;
import com.ruyuan.commodity.common.mamager.GoodsInfoQueryManager;
import com.ruyuan.commodity.model.goods.dto.GoodsSkuQuantityVO;
import com.ruyuan.commodity.model.goods.vo.CacheGoods;
import com.ruyuan.commodity.model.goods.vo.GoodsQuantityVO;
import com.ruyuan.commodity.model.goods.vo.GoodsSkuVO;
import com.ruyuan.commodity.open.api.annotation.Auth;
import com.ruyuan.commodity.open.api.model.errorcode.GoodsErrorCode;
import com.ruyuan.commodity.open.api.model.goods.enums.QuantityType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品库存维护
 */
@Api(value = "商家中心商品库存单独维护api")
@RestController
@RequestMapping("/seller/goods/{goodsId}/quantity")
@Validated
public class GoodsQuantityController {

	public static final Logger LOG = LoggerFactory.getLogger(GoodsQuantityController.class);
	/**
	 * 商品查询业务管理器
	 */
	@Autowired
	private GoodsInfoQueryManager goodsInfoQueryManager;
	/**
	 * 商品库存业务管理器
	 */
	@Autowired
	private GoodsQuantityManager goodsQuantityManager;

	@Auth
	@ApiOperation(value = "商家单独维护库存接口", notes = "商家单独维护库存接口时使用")
	@PutMapping
	public Map<String, Boolean> updateQuantity(@Valid @RequestBody List<GoodsSkuQuantityVO> skuQuantityList,
											   @PathVariable("goodsId") Long goodsId)  {
		Map<String, Boolean> result = new HashMap<>(1);
		try {
			CacheGoods goods = goodsInfoQueryManager.getFromCache(goodsId);

			if (goods == null) {
				throw new ServiceException(GoodsErrorCode.E307.code(), "未找到该商品信息");
			}

			// 原有的sku集合
			List<GoodsSkuVO> skuList = goods.getSkuList();
			Map<Long,GoodsSkuVO> skuMap = new HashMap<>(skuList.size());
			for (GoodsSkuVO sku : skuList) {
				skuMap.put(sku.getSkuId(), sku);
			}

			// 要更新的库存列表
			List<GoodsQuantityVO> stockList = new ArrayList<>();

			for (GoodsSkuQuantityVO quantity : skuQuantityList) {
				if (quantity.getQuantityCount() == null || quantity.getQuantityCount() < 0 ) {
					throw new ServiceException(GoodsErrorCode.E307.code(), "sku总库存不能为空或负数");
				}

				GoodsSkuVO sku = skuMap.get(quantity.getSkuId());
				if (sku == null) {
					throw new ServiceException(GoodsErrorCode.E307.code(), "商品sku不存在");
				}
				// 待发货数
				Integer waitRogCount = sku.getQuantity() - sku.getEnableQuantity();
				//判断库存是否小于待发货数
				if (quantity.getQuantityCount() < waitRogCount) {
					throw new ServiceException(GoodsErrorCode.E307.code(), "sku库存数不能小于待发货数");
				}

				// 实际库存
				GoodsQuantityVO actualQuantityVo = new GoodsQuantityVO();
				// 用传递的数量-现有的，就是变化的，如传递的是2000，原来是200，则就+1800，如果传递的是100，原来是200则就是-100
				int stockNum = quantity.getQuantityCount() - sku.getQuantity();
				actualQuantityVo.setQuantity(stockNum);
				actualQuantityVo.setGoodsId(goodsId);
				actualQuantityVo.setQuantityType(QuantityType.actual);
				actualQuantityVo.setSkuId(quantity.getSkuId());
				stockList.add(actualQuantityVo);

				// clone 一个quantity vo 设置为更新可用库存
				try {
					GoodsQuantityVO enableVo =(GoodsQuantityVO)	actualQuantityVo.clone();
					enableVo.setQuantityType(QuantityType.enable);
					stockList.add(enableVo);
				} catch (CloneNotSupportedException e) {
					throw new ServiceException(GoodsErrorCode.E307.code(), "goodsQuantityVo clone error");
				}
			}

			// 更新库存
			goodsQuantityManager.updateSkuQuantity(stockList);

			result.put("result", true);

			return result;
		} catch (Exception e) {
			LOG.error("批量添加商品SKU库存发生异常", e);
			result.put("result", false);
			return result;
		}
	}

}
